package jhavelogger.parser;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jhavelogger.models.AcceptedConnection;
import jhavelogger.models.UsernameLookup;
import jhavelogger.models.JHaveLog;
import jhavelogger.models.SendAlgorithmToClient;
import jhavelogger.models.UnparsedLog;

/**
 * Parses "sendToClient 400" log messages. This specifies which algorithm
 * was actually sent to the client.
 * 
 * @author Jared Schlicht
 */
public class SendAlgorithmToClientFactory implements LogFactory {
    private Pattern pattern;

    public SendAlgorithmToClientFactory() {
	// "11/12/11 8:18 AM - FINE: sendtoClient - 400 chainedhashing/shc_exercise_3 gaigs"
	final String datePattern = "\\d{1,2}/\\d{1,2}/\\d{2}";
	final String timePattern = "\\d{1,2}:\\d{1,2} (?:AM|PM)";
	final String algorithmLookupRegex = "^(" + datePattern + "\\s+" +
		timePattern + ")\\s+-\\s+FINE:\\s+sendtoClient\\s+-\\s+400\\s+(\\S+)";
	this.pattern = Pattern.compile(algorithmLookupRegex, Pattern.CASE_INSENSITIVE);
    }

    @Override
    public JHaveLog create(UnparsedLog log) {
	Matcher matcher = this.pattern.matcher(log.getMessage());
	if (matcher.find()) {
	    String date = matcher.group(1);
	    String algorithm = matcher.group(2);
	    return new SendAlgorithmToClient(log.getSource(), new Date(date), algorithm);
	}
	return null;
    }

}
